package com.shuyuansystem.service.impl;

import com.shuyuansystem.dao.OrderMapper;
import com.shuyuansystem.dao.ProductMapper;
import com.shuyuansystem.entity.Result;
import com.shuyuansystem.pojo.CheckOrders;
import com.shuyuansystem.pojo.Order;
import com.shuyuansystem.pojo.ShoppingCart;
import com.shuyuansystem.service.OrderService;
import com.shuyuansystem.utils.JWTUtils;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.shuyuansystem.utils.PageResult;
import com.shuyuansystem.utils.QueryPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;
//
//    @Override
//    public Map<String, Object> buyProduct(int productId, String token) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 验证 Token
//            DecodedJWT decodedJWT = JWTUtils.verify(token);
//
//            // 从 Token 中获取用户 ID
//            int userId = Integer.parseInt(decodedJWT.getClaim("id").asString());
//
//            // 创建订单对象
//            Order order = new Order();
//            order.setId(userId);
////            order.setProduct_id(productId);
//            order.setStatus_id(1); // 假设初始状态为 1
//
//            // 插入订单信息到数据库
//            int rowsAffected = orderMapper.insertOrder(order);
//            if (rowsAffected > 0) {
//                response.put("success", true);
//                response.put("message", "购买成功");
//            } else {
//                response.put("success", false);
//                response.put("message", "购买失败");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.put("success", false);
//            response.put("message", "Token 验证失败或插入订单失败: " + e.getMessage());
//        }
//        return response;
//    }

    @Override
    public Result addShoppingcart(ShoppingCart shoppingCart) {
        // 检查购物车中是否已经存在该用户的该商品记录
        ShoppingCart existingCartItem = orderMapper.getShoppingCartItem(shoppingCart);
        if (existingCartItem != null) {
            // 如果存在，则数量加 1
            int newQuantity = existingCartItem.getQuantity() + 1;
            existingCartItem.setQuantity(newQuantity);
            orderMapper.updateShoppingCartQuantity(existingCartItem);
        } else {
            // 如果不存在，则插入新记录，数量初始为 1
            shoppingCart.setQuantity(1);
            orderMapper.addShoppingcart(shoppingCart);
            existingCartItem = orderMapper.getShoppingCartItem(shoppingCart);
        }
        return new Result(true, "加入购物车成功", existingCartItem.getQuantity());
    }
    @Override
    public Result reduceShoppingCart(ShoppingCart shoppingCart) {
        // 检查购物车中是否已经存在该用户的该商品记录
        ShoppingCart existingCartItem = orderMapper.getShoppingCartItem(shoppingCart);
        if (existingCartItem != null) {
            int currentQuantity = existingCartItem.getQuantity();
            int newQuantity = currentQuantity - 1;
            if (newQuantity <= 0) {
                // 如果减少后数量小于等于 0，则删除该记录
                orderMapper.deleteShoppingCartItem(shoppingCart);
                newQuantity = 0;
            } else {
                // 否则更新数量
                existingCartItem.setQuantity(newQuantity);
                orderMapper.updateShoppingCartQuantity(existingCartItem);
            }
            return new Result(true, "减少购物车商品成功", newQuantity);
        }
        return new Result(false, "购物车中不存在该商品", 0);
    }

    @Override
    public Integer getShoppingCartQuantity(ShoppingCart shoppingCart) {
        ShoppingCart existingCartItem = orderMapper.getShoppingCartItem(shoppingCart);
        if (existingCartItem != null) {
            return existingCartItem.getQuantity();
        }
        return 0;
    }
    /**
     * 分页查询商品信息
     * @param queryPageBean 分页查询条件
     * @return 分页结果
     */
    public PageResult<ShoppingCart> getProductInfoByPage(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        int offset = (currentPage - 1) * pageSize;
        queryPageBean.setCurrentPage(offset); // 修改 QueryPageBean 的 currentPage 为 offset

        List<ShoppingCart> shoppingCartList = orderMapper.getProductInfoByPage(queryPageBean);
        Long total = orderMapper.getTotalProductInfoCount();

        return new PageResult<>(total, shoppingCartList);
    }
    @Override
    public Integer getProductIdByName(String productName) {
        return productMapper.getProductIdByName(productName);
    }

    public void synchronizeOrderListWithShoppingCart(Integer userId) {
        // 获取购物车中的商品信息
        List<ShoppingCart> shoppingCarts = orderMapper.getProductIdAndQuantityById(userId.toString());
        List<Integer> productIds = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            productIds.add(cart.getProductId());
        }

        // 获取商家 - 产品关联信息
        List<Map<String, Object>> merchantProductAssociations = orderMapper.getMerchantProductAssociationByProductIds(productIds);
        Map<Integer, String> productIdToMerchantIdMap = new HashMap<>();
        for (Map<String, Object> association : merchantProductAssociations) {
            Integer productId = (Integer) association.get("product_id");
            String merchantId = association.get("id").toString();
            productIdToMerchantIdMap.put(productId, merchantId);
        }

        // 获取产品名称
        Map<Integer, String> productIdToNameMap = new HashMap<>();
        // 假设这里有获取产品名称的方法，需要根据实际情况完善
        // 例如可以在OrderMapper中添加根据productId获取productName的方法
        for (int productId : productIds) {
            // 这里只是示例，实际需要实现具体的获取逻辑
            productIdToNameMap.put(productId, "");
        }

        // 获取订单表中的订单信息
        List<CheckOrders> orderList = orderMapper.getOrdersByUserId(userId.toString());
        Map<String, String> orderMerchantProductMap = new HashMap<>();
        for (CheckOrders order : orderList) {
            String key = order.getMerchant_id() + ":" + order.getProduct_name();
            orderMerchantProductMap.put(key, key);
        }

        // 处理订单表数据
        for (ShoppingCart cart : shoppingCarts) {
            String merchantId = productIdToMerchantIdMap.get(cart.getProductId());
            String productName = productIdToNameMap.get(cart.getProductId());
            if (merchantId != null && productName != null) {
                String key = merchantId + ":" + productName;
                if (!orderMerchantProductMap.containsKey(key)) {
                    // 订单表中不存在，插入数据
                    CheckOrders newOrder = new CheckOrders();
                    newOrder.setUser_id(userId.toString());
                    newOrder.setMerchant_id(merchantId);
                    newOrder.setProduct_name(productName);
                    newOrder.setQuantity(cart.getQuantity());
                    // 假设这里需要根据实际情况计算总价
                    newOrder.setTotal_price(0);
                    orderMapper.insertOrderList(List.of(newOrder));
                } else {
                    // 存在则可以选择更新数量等操作，这里暂不处理更新逻辑
                }
                orderMerchantProductMap.remove(key);
            }
        }

        // 删除订单表中购物车不存在的商品订单
        for (String key : orderMerchantProductMap.keySet()) {
            String[] parts = key.split(":");
            String merchantId = parts[0];
            String productName = parts[1];
            CheckOrders orderToDelete = new CheckOrders();
            orderToDelete.setUser_id(userId.toString());
            orderToDelete.setMerchant_id(merchantId);
            orderToDelete.setProduct_name(productName);
            orderMapper.deleteOrder(orderToDelete);
        }
    }
    /**
     * 获取指定用户 ID 对应的购物车产品 ID 列表
     * @param userId 用户 ID
     * @return 产品 ID 列表
     */
    public List<ShoppingCart> getShoppingCartProductIdsByUserId(String userId) {
        return orderMapper.getProductIdAndQuantityById(userId);
    }
    // 新增方法：根据产品 ID 列表查询对应的商家 ID
    public List<Map<String, Object>> getMerchantIdsByProductIds(List<Integer> productIds) {
        return orderMapper.getMerchantIdsByProductIds(productIds);
    }
    // 新增方法：根据产品 ID 列表查询对应的产品名称
    public List<Map<String, Object>> getProductNamesByProductIds(List<Integer> productIds) {
        return orderMapper.getProductNamesByProductIds(productIds);
    }
    /**
     * 获取 order_list 表中所有的商家 ID 及对应的商品名称
     * @return 包含商家 ID 和商品名称的 Map 列表
     */
    public List<Map<String, Object>> getMerchantIdAndProductNameFromOrderList() {
        return orderMapper.getMerchantIdAndProductNameFromOrderList();
    }
    /**
     * 根据商家 ID 和商品名称删除订单表中的记录
     * @param deleteList 包含商家 ID 和商品名称的 Map 列表
     * @return 删除的记录数
     */
    public int deleteOrdersByMerchantAndProduct(List<Map<String, Object>> deleteList) {
        return orderMapper.deleteOrdersByMerchantAndProduct(deleteList);
    }
}